package com.toocms.jinjuhang.ui.mine.order

import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.order_info.OrderItemData
import com.toocms.jinjuhang.dialog.hint.HintDialog
import com.toocms.jinjuhang.dialog.order_cancel.OrderCancelDialog
import com.toocms.jinjuhang.ui.mine.order.details.OrderDetailsFgt
import com.toocms.jinjuhang.ui.mine.order.logistics_details.LogisticsDetailsFgt
import com.toocms.jinjuhang.ui.mine.payment.PaymentFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.jinjuhang.widget.view_model.showToast
import com.toocms.tab.base.BaseActivity
import com.toocms.tab.base.ItemViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger

class MyOrderItemModel(viewModel: MyOrderModel, val item: ObservableField<OrderItemData>) :
    ItemViewModel<MyOrderModel>(viewModel) {
    val serviceItems by lazy {
        val result = ObservableArrayList<OrderServiceItemModel>()
        LogUtils.e(item.get()?.goods_list?.size ?: 0)
        item.get()?.goods_list?.forEach {
            it.order_id = item.get()?.order_id
            result += OrderServiceItemModel(viewModel, ObservableField(it))
        }
        result
    }
    val serviceItemBinding =
        ItemBinding.of<OrderServiceItemModel>(BR.orderServiceItemModel, R.layout.item_order_service)

    val priceObservableField by lazy {
        val content = when (item.get()?.order_type) {
            Constants.Extra.ORDER_TYPE_INTEGRAL -> {
                "${
                    when (viewModel.currentOrderStatus) {
                        OrderStatus.AFTER_SALE -> item.get()?.refund_amounts ?: "0.00"
                        else -> item.get()?.pay_amounts ?: "0.00"
                    }
                }${StringUtils.getString(R.string.str_integral)}"
            }
            else -> {
                "${StringUtils.getString(R.string.str_money_symbol)}${
                    when (viewModel.currentOrderStatus) {
                        OrderStatus.AFTER_SALE -> item.get()?.refund_amounts ?: "0.00"
                        else -> item.get()?.pay_amounts ?: "0.00"
                    }
                }"
            }
        }
        ObservableField(content)
    }

    val itemClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        item.get()?.apply {
            val status =
                if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
                else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
            val bundle = Bundle()
            if (OrderStatus.AFTER_SALE == status) {
                bundle.putString(Constants.BundleKey.KEY_REFUND_ID, refund_id)
            } else {
                bundle.putString(Constants.BundleKey.KEY_ORDER_ID, order_id)
            }
            viewModel.startFragment(OrderDetailsFgt::class.java, bundle)
        }
    })
    val isVisibleFunction0 by lazy {
        val status =
            if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
            else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
        val content = when (status) {
            OrderStatus.AWAIT_PAYMENT -> true //TODO 支付
            OrderStatus.AWAIT_RECEIVING -> true //TODO 确认收货
            else -> false
        }
        ObservableBoolean(content)
    }
    val function0Hint by lazy {
        val status =
            if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
            else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
        val content = when (status) {
            OrderStatus.AWAIT_PAYMENT -> StringUtils.getString(R.string.str_payment) //TODO 支付
            OrderStatus.AWAIT_RECEIVING -> StringUtils.getString(R.string.str_confirm_receiving) //TODO 确认收货
            else -> ""
        }
        ObservableField(content)
    }

    val function0ClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
//        viewModel.startFragment(OrderEvaluateFgt::class.java)
        item.get()?.apply {
            val status =
                if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
                else OrderStatus.code2Status(status?.toInt() ?: OrderStatus.ALL.code)
            when (status) {
                OrderStatus.AWAIT_PAYMENT -> { //TODO 支付
                    val bundle = Bundle()
                    bundle.putString(Constants.BundleKey.KEY_ORDER_SN, order_sn)
                    bundle.putString(Constants.BundleKey.KEY_PAYMENT_SUM, pay_amounts)
                    viewModel.startFragment(PaymentFgt::class.java, bundle)
                }
                OrderStatus.AWAIT_RECEIVING -> { //TODO 确认收货
                    HintDialog().apply {
                        content = StringUtils.getString(R.string.str_order_receiving_hint)
                        onPositiveClickListener = {
                            val params = mutableMapOf<String, String?>()
                            params["member_id"] = UserRepository.user.member_id
                            params["order_id"] = order_id
                            viewModel.requestData(Urls.OrderInfo.SIGN_FOR,
                                params,
                                resultClass = String::class.java,
                                result = {
                                    showToast(it)
                                    Messenger.getDefault()
                                        .sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ORDER)
                                })
                        }
                        show(
                            (ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager,
                            null
                        )
                    }
                }
                else -> {}
            }
        }
    })

    val isVisibleFunction1 by lazy {
        val status =
            if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
            else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
        val content = when (status) {
            OrderStatus.AWAIT_PAYMENT -> true //TODO 取消订单
            OrderStatus.AWAIT_SHIPMENTS -> false //TODO 取消订单
            OrderStatus.AWAIT_RECEIVING, OrderStatus.AWAIT_EVALUATE -> true //TODO 查看物流
            else -> false
        }
        ObservableBoolean(content)
    }

    val function1Selected by lazy {
        val status =
            if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
            else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
        val content = when (status) {
            OrderStatus.AWAIT_PAYMENT -> false //TODO 取消订单
            OrderStatus.AWAIT_SHIPMENTS -> false //TODO 取消订单
            OrderStatus.AWAIT_RECEIVING, OrderStatus.AWAIT_EVALUATE -> true //TODO 查看物流
            else -> false
        }
        ObservableBoolean(content)
    }
    val function1Hint by lazy {
        val status =
            if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
            else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
        val content = when (status) {
            OrderStatus.AWAIT_PAYMENT -> StringUtils.getString(R.string.str_cancel_order) //TODO 取消订单
            OrderStatus.AWAIT_SHIPMENTS -> StringUtils.getString(R.string.str_cancel_order) //TODO 取消订单
            OrderStatus.AWAIT_RECEIVING, OrderStatus.AWAIT_EVALUATE -> StringUtils.getString(R.string.str_view_logistics) //TODO 查看物流
            else -> ""
        }
        ObservableField(content)
    }

    val function1ClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val status =
            if (OrderStatus.AFTER_SALE == viewModel.currentOrderStatus) OrderStatus.AFTER_SALE
            else OrderStatus.code2Status(item.get()?.status?.toInt() ?: OrderStatus.ALL.code)
        when (status) {
            OrderStatus.AWAIT_PAYMENT -> { //TODO 取消订单
                cancelOrder(item.get()?.order_id)
            }
            OrderStatus.AWAIT_SHIPMENTS -> { //TODO 取消订单
                cancelOrder(item.get()?.order_id)
            }
            OrderStatus.AWAIT_RECEIVING, OrderStatus.AWAIT_EVALUATE -> { //TODO 查看物流
                val bundle = Bundle()
                bundle.putString(
                    Constants.BundleKey.KEY_LOGISTICS_NUMBER,
                    item.get()?.logistics_number
                )
                viewModel.startFragment(LogisticsDetailsFgt::class.java, bundle)
            }
            else -> {

            }
        }
    })

    private fun cancelOrder(orderId: String?) {
        if (orderId.isNullOrEmpty()) return
        OrderCancelDialog().apply {
            this.type = Constants.Extra.REASON_TYPE_CANCELLATION_REASONS
            this.orderId = orderId
            onSucceedListener = {
                Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ORDER)
            }
            show((ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager, null)
        }
    }
}